import axios from 'axios'
import * as util from '@/util'
import TipUtil from '@/util/TipUtil'

let http = axios.create({
  baseURL: '',
  timeout: 20 * 1000
})

http.defaults.headers.post['Content-Type'] = 'application/json'

http.interceptors.request.use((config) => {
  // url处理
  config.url = process.env.VUE_APP_ROOT + config.url

  // 强制调用时传递method用大写
  let method = config.method || 'get'

  if (method !== 'get') {
    // 强制传递了method
  } else if (config.params) {
    config.method = 'get'
  } else if (config.data) {
    config.method = 'post'
  }

  let token = util.getToken()
  if (token) {
    config.headers.Token = token
  }

  // FormData
  if (config.data && typeof config.data.append === 'function') {
    config.headers['Content-Type'] = 'multipart/form-data'
    config.timeout = 60 * 1000
  }

  return config
}, error => {
  return Promise.reject(error)
})

http.interceptors.response.use(response => {
  switch (response.status) {
    case 401:
      return util.toLogin()
    case 200:
      if (response.data.Code === api.CodeSuccess) {
        return Promise.resolve(response.data)
      } else {
        TipUtil.error(response.data.Msg)
        return Promise.reject(response)
      }
    default:
      TipUtil.error(response.data.Msg)
      return Promise.reject(response)
  }
}, error => {
  if (error.code === 'ECONNABORTED') {
    TipUtil.error('连接超时')
  } else if (error.response) {
    let status = error.response.status
    if (status === 504) {
      TipUtil.error('连接超时')
    } else if (status === 404) {
      TipUtil.error(`${error.response.request.responseURL}不存在`)
    }
  } else if (!util.isOnLine()) {
    TipUtil.error('请检测网络连接')
  }
  return Promise.reject(error.response)
})

export default http
